package com.rabbitmq.RabbitMQ;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.Entity.RabbitMQ;
import com.rabbitmq.Entity.RabbitMQInfo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class RabbitMQReceiver {

    @RabbitHandler
    @RabbitListener(queues = RabbitMQ.QUEUE_HELLOTOSTRING)
    public void receiveString(String context,Channel channel, Message message) throws IOException {
        System.out.println("MQReceiver收到内容:" + context);
        System.out.println("MQReceiver收到时间:" + new Date());
        try {
            //告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            System.out.println("MQReceiver:receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            //丢弃这条消息
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
            System.out.println("MQReceiver:receiver fail");
        }
    }

    @RabbitHandler
    @RabbitListener(queues = RabbitMQ.QUEUE_HELLOOBJ)
    public void receiveObj(RabbitMQInfo rabbit, Channel channel, Message message) throws IOException {
        System.out.println("MQReceiver收到内容:" + JSON.toJSONString(rabbit));
        System.out.println("MQReceiver收到时间:" + new Date());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("MQReceiver:receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("MQReceiver:receiver fail");
        }
    }

    @RabbitHandler
    @RabbitListener(queues = RabbitMQ.QUEUE_DELAY_INFO)
    public void listenerDelayQueue(RabbitMQInfo rabbit, Message message, Channel channel) {
        System.out.println("MQReceiver收到内容:" + JSON.toJSONString(rabbit));
        System.out.println("MQReceiver收到时间:" + new Date());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("MQReceiver:receiver success");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("MQReceiver:receiver fail");
        }
    }
}
